<?php
namespace App\Http\Controllers\Laifei\Work;

use App\Http\Controllers\Controller;
use App\Models\Common\Common;
use App\Models\Tools\Data;
use App\Models\Work;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LaifeiWorkCancelController extends Controller
{

    public function index()
    {

        $all = $this->all;
        $work_id = $all['work_id'];
        $remark = $all['remark'];

        try{
            DB::beginTransaction();
            // 查询订单、工单、余量信息并锁表
            $work = Work::exploreWorkAndX($work_id);
            $order = Work::exploreOrderAndX($work['eo_id']);
            $remaining = Work::exploreRemainingAndX($order['we_id'], $order['channel_id']);

            // 如果订单已结算，不可关闭
            if($work['status'] === Data::DATA_DB_EXPLORE_WORK_STATUS_SETTLEMENT){
                DB::rollBack();
                return $this->setReturnJson(-1,'此工单已结算，不允许关闭');
            }

            // 修改工单状态
            DB::table('explore_work')
                ->where('work_id','=',$work_id)
                ->update([
                    'status'=>Data::DATA_DB_EXPLORE_WORK_STATUS_ERROR,
                    'error_reason'=>Data::DATA_DB_EXPLORE_WORK_ERROR_REASON_CANCEL,
                    'reason_detail' => $remark,
                ]);
            // 记录工单日志
            DB::table('explore_work_log')->insert([
                'work_id'=>$work_id,
                'action'=>Data::DATA_DB_EXPLORE_WORK_ACTION_CANCEL,
                'user_id'=>$this->userInfo['id'],
                'remark'=>'管理员【'.$this->userInfo['name'].'】关闭工单：'.$remark,
            ]);

            // 修改订单状态
            Work::workCancelToOrder($order);
            // 修改发单者剩余数量并记录日志
            Work::workCancelToRemaining($remaining);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            Log::error(LaifeiWorkCancelController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'关闭失败',['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }

        //  发送验收拒回微信通知（发送给商家）
        $data = [
            'first' => '您有一个达人已接单的探店已被取消。',
            'keyword1' => '达人探店',
            'keyword2' => '管理员【'.$this->userInfo['name'].'】',
            'keyword3' => date('Y-m-d H:i:s'),
            'keyword4' => $remark,
            'remark' => '探店次数余量已退还到您的账户，您可以再次申请探店，点击查看详情。',
        ];
        //发送通知
        $openid = DB::table('lottery_users')->where('we_id','=',$work['apply_we_id'])->value('openid');
        Common::sendLaifeiMessage($openid,'work_cancel',$data,'/history?tab=1');

        //  发送验收拒回微信通知（发送给达人）
        $data = [
            'first' => '您有探店工单已被取消。',
            'keyword1' => '达人探店',
            'keyword2' => '管理员【'.$this->userInfo['name'].'】',
            'keyword3' => date('Y-m-d H:i:s'),
            'keyword4' => $remark,
            'remark' => '点击查看详情',
        ];
        //发送通知
        $openid = DB::table('lottery_users')->where('we_id','=',$work['receiver_we_id'])->value('openid');
        Common::sendLaifeiMessage($openid,'work_cancel',$data,'/talent/history?tab=1');
        return $this->setReturnJson(0,'success');

    }

}
